package net.jgrm.common.util;

import javax.servlet.http.HttpServletRequest;

/**
 * IP工具类
 *
 * @author service-common
 */
public class IPUtil {

    /**
     * 私有构造函数
     */
    private IPUtil() {
        // 工具类不允许实例化
    }

    /**
     * 获取客户端真实IP地址
     *
     * @param request HTTP请求对象
     * @return 客户端IP地址
     */
    public static String getRemoteIp(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 如果通过多级代理，会有多个IP，取第一个非unknown的IP
        if (ip != null && ip.contains(",")) {
            final String[] arr = ip.split(",");
            for (final String str : arr) {
                if (!"unknown".equalsIgnoreCase(str.trim())) {
                    ip = str.trim();
                    break;
                }
            }
        }

        return ip;
    }

    /**
     * 获取客户端真实IP地址（兼容方法）
     *
     * @param request HTTP请求对象
     * @return 客户端IP地址
     */
    public static String getRealIp(HttpServletRequest request) {
        return getRemoteIp(request);
    }

    /**
     * 判断是否为内网IP
     *
     * @param ip IP地址
     * @return true:内网IP false:外网IP
     */
    public static boolean isInternalIp(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }

        // 本地回环地址
        if ("127.0.0.1".equals(ip) || "localhost".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            return true;
        }

        try {
            String[] parts = ip.split("\\.");
            if (parts.length != 4) {
                return false;
            }

            int a = Integer.parseInt(parts[0]);
            int b = Integer.parseInt(parts[1]);

            // A类内网：10.0.0.0 ~ 10.255.255.255
            if (a == 10) {
                return true;
            }
            // B类内网：172.16.0.0 ~ 172.31.255.255
            if (a == 172 && b >= 16 && b <= 31) {
                return true;
            }
            // C类内网：192.168.0.0 ~ 192.168.255.255
            if (a == 192 && b == 168) {
                return true;
            }
        } catch (NumberFormatException e) {
            return false;
        }

        return false;
    }
}